<template>
  <el-dialog
    title="专区"
    :visible.sync="dialogShow"
    width="80%"
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <div>
      <search-form
        :search-config="searchConfig"
        :label-width="100"
        @clear="clearSearch"
        @search="handleSearch"
      />
    </div>
    <div class="table-list-box">
      <el-table
        ref="multipleTable"
        v-loading="tableLoading"
        :data="tableData"
        border
        height="160"
        header-row-class-name="table-list-header"
        :row-class-name="tableRowClassName"
        tooltip-effect="dark"
        style="width: 100%"
        @row-click="selectRow"
        @select="selectTable"
        @select-all="selectionAll"
        @selection-change="selectChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号" />
        <el-table-column prop="styleCode" label="编码" />
        <el-table-column prop="styleName" label="名称" />
      </el-table>
    </div>
    <div class="pagination-box">
      <div class="pagination-container">
        <el-pagination
          :current-page.sync="currentPage"
          :page-sizes="pageSizelist"
          :page-size="pageSize"
          layout="sizes, prev, pager, next, slot"
          :total="allTotal === 0 ? total : allTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <span class="el-pagination__jump">前往
            <el-input-number
              v-model="jumpPage"
              :controls="false"
              :min="1"
              @blur="showEnter"
              @keyup.enter.native="showEnter"
            />页</span>
        </el-pagination>
        <div v-show="total <= pageSize" class="pagination-info">当前显示
          <span>{{ handlePageRange(pageSize, currentPage) }}</span>，共
          <span class="total"> {{ tableData.length }} </span> 条记录
        </div>
        <div v-show="total > pageSize" class="pagination-info">当前显示
          <span>{{ handlePageRange(pageSize, currentPage) }}</span>，共
          <span :class="[allTotal === 0 && total !== 0 ? 'total next-page': 'total']" @click="newEnter"> {{ allTotal === 0 && total !== 0 ? total-1 +'+': allTotal }}  </span> 条记录
        </div>
      </div>
    </div>
    <div style="margin:10px 0;display:inlnk-black;font-size: 14px;">已选择
      <span style="color:#0f3eea;">{{ selectedData.length }}</span>条数据
    </div>
    <div class="table-list-box">
      <el-table
        ref="chosenTable"
        :data="selectedData"
        border
        height="160"
        header-row-class-name="table-list-header"
        highlight-current-row
        tooltip-effect="dark"
        style="width: 100%"
      >
        <el-table-column prop="styleCode" label="编码" />
        <el-table-column prop="styleName" label="名称" />
        <el-table-column label="操作" width="60">
          <template slot-scope="scope">
            <el-button
              type="text"
              style="color:#3dc094; cursor: pointer;"
              @click="deleteChose(scope.$index,scope.row)"
            >删 除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="handleClose">取 消</el-button>
      <el-button type="primary" size="mini" @click="determineChosen">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getStyleData } from '@/api/marketConstruction'
export default {
  name: 'Recommend',
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      tableLoading: false,
      otherFilter: [],
      recommendProgramList: [],
      seriesNameList: [],
      searchConfig: [
        { label: '编码', prop: 'styleCode', type: 'text', value: '' },
        { label: '名称', prop: 'styleName', type: 'text', value: '' }
      ],
      selectedData: [],
      tableData: [],
      otherFilters: [{ 'id': 'enable', 'property': 'enable', 'operator': '=', 'value': 1 }],
      pageSize: 5,
      pageSizelist: [5, 10, 15, 20],
      currentPage: 1,
      total: '',
      jumpPage: '',
      allTotal: 0,
      formData: {
        seriesName: '',
        seriesCode: '',
        productName: '',
        productRadio: '1',
        productCode: '' // 62323901101 669325001
      },
      allOtherFilter: [],
      queryArr: []
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.selectedData = []
          this.$nextTick(() => {
            this.$refs.multipleTable.clearSelection()
          })
        }
      }
    }
  },
  async created() {
    this.modelListAll(1, 5, false, JSON.stringify(this.otherFilters))
  },
  mounted() {},
  methods: {
    // 获取搜索条件
    handleSearch(data) {
      this.currentPage = 1
      this.pageSize = 5
      this.onParams(data)
    },
    modelListAll(currentPage, pageSize, onlyCountFlag, otherFilters) {
      this.tableLoading = true
      const dataForm = new FormData()
      dataForm.append('page', currentPage)
      dataForm.append('rows', pageSize)
      dataForm.append('onlyCountFlag', onlyCountFlag)
      dataForm.append('filtersRaw', otherFilters)
      getStyleData(dataForm).then(res => {
        if (res.success && res.data && res.data.records) {
          if (!onlyCountFlag) {
            this.tableData = res.data.records
            this.total = res.data.total
            this.allTotal = 0
            if (this.total <= this.currentPage * this.pageSize) {
              this.allTotal = this.total
            }
            const selectIds = this.selectedData.map(e => {
              return e.id
            })
            // 表格数据对比是否存在已选择数据并对其勾选
            this.tableData.forEach(item => {
              if (selectIds.includes(item.id)) {
                this.$nextTick(() => {
                  this.$refs.multipleTable.toggleRowSelection(item)
                })
              }
            })
          } else {
            this.allTotal = res.data.total
            this.total = res.data.total
            this.currentPage = res.data.page
          }
        }
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 确定
    determineChosen() {
      if (!this.selectedData.length) {
        this.$message.warning('请选择专区')
        return
      }
      this.$emit('addSeries', this.selectedData)
      this.handleClose()
      this.dialogShow = false
    },
    // 前往第几页
    showEnter(ev) {
      this.jumpPage = ev.srcElement.value
      this.getTotal(this.jumpPage)
    },
    // 获取总数据条数
    newEnter() {
      this.getTotal(this.currentPage)
    },
    // 当操作在非第一页时，跳回第一页
    jumpToFirstPage() {
      this.currentPage = 1 // 不在第一页搜索时，调回第一页显示
      this.jumpPage = 1
      this.allTotal = 0
      this.total = 0
    },
    // 分页，获取下一页数据
    handleCurrentChange(currentPage) {
      this.jumpPage = currentPage
      this.currentPage = currentPage
      this.$refs.multipleTable.clearSelection()
      this.$refs.chosenTable.clearSelection()
      this.modelListAll(this.currentPage, this.pageSize, false, JSON.stringify(this.this.allOtherFilter))
    },
    // 分页数据获取---> this.$refs.chosenTable/multipleTable.clearSelection
    handleSizeChange(val) {
      this.pageSize = val
      this.$refs.multipleTable.clearSelection()
      this.$refs.chosenTable.clearSelection()
      this.jumpToFirstPage()
      this.modelListAll(this.currentPage, this.pageSize, false, JSON.stringify(this.this.allOtherFilter))
    },
    // 计算当前数据范围 如:1-20
    handlePageRange(size, currentPage) {
      const start = size * (currentPage - 1) + 1
      const end = size * currentPage
      const pageRange = `${start}-${end}`
      return pageRange
    },
    // 获取数据总条数
    getTotal(val) {
      if (this.allTotal !== 0) return
      let page = this.currentPage
      if (val) {
        page = val
      }
      this.modelListAll(this.currentPage, page, true, JSON.stringify(this.this.allOtherFilter))
      this.$nextTick(() => {
        this.modelListAll(this.currentPage, page, false, JSON.stringify(this.this.allOtherFilter))
      })
    },
    onParams(data) {
      this.tableLoading = true
      this.allOtherFilter = [...this.otherFilters, ...data.filtersRaw]
      const dataForm = new FormData()
      dataForm.append('page', this.currentPage)
      dataForm.append('rows', this.pageSize)
      dataForm.append('onlyCountFlag', false)
      dataForm.append('filtersRaw', JSON.stringify(this.allOtherFilter))
      getStyleData(dataForm).then(res => {
        if (res.success && res.data && res.data.records) {
          this.tableData = res.data.records
          this.total = res.data.total
          this.allTotal = 0
          if (this.total <= this.currentPage * this.pageSize) {
            this.allTotal = this.total
          }
          const selectIds = this.selectedData.map(e => {
            return e.id
          })
          // 表格数据对比是否存在已选择数据并对其勾选
          this.tableData.forEach(item => {
            if (selectIds.includes(item.id)) {
              this.$nextTick(() => {
                this.$refs.multipleTable.toggleRowSelection(item)
              })
            }
          })
        }
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    handleClose() {
      this.dialogShow = false
      this.$emit('update:visible', false)
    },
    selectionAll(val) {
      const selectIds = this.selectedData.map(e => {
        return e.id
      })
      val.length &&
        val.forEach(item => {
          if (!selectIds.includes(item.id)) {
            this.selectedData = this.selectedData.concat(item)
          }
        })
      if (!val.length) {
        this.tableData.forEach(item => {
          this.selectedData.forEach((s, index) => {
            if (s.id === item.id) {
              this.selectedData.splice(index, 1)
            }
          })
        })
      }
    },
    // 产品数据手动勾选
    selectTable(val, row) {
      if (this.selectedData.length > 0) {
        // 筛选已勾选的code
        const codeList = val.map(e => {
          return e.id
        })
        if (codeList.includes(row.id)) {
          // 判断是勾选还是取消
          this.selectedData = this.selectedData.concat(row)
        } else {
          this.selectedData.forEach((item, index) => {
            if (item.id === row.id) {
              this.selectedData.splice(index, 1)
            }
          })
        }
      } else {
        this.selectedData = val
      }
      this.$nextTick(() => {
        this.selectedData.forEach(item => {
          this.$refs.chosenTable.toggleRowSelection(item, true)
        })
      })
    },
    // 产品数据手动勾选
    selectRow(row) {
      if (this.selectedData.length > 0) {
        const arr = JSON.parse(JSON.stringify(this.selectedData))
        // 筛选已勾选的code
        const codeList = arr.map(e => {
          return e.id
        })
        if (!codeList.includes(row.id)) {
          // 判断是勾选还是取消
          this.selectedData = arr.concat(row)
          this.$nextTick(() => {
            this.selectedData.forEach(item => {
              this.$refs.multipleTable.toggleRowSelection(item, true)
            })
          })
        } else {
          this.selectedData.forEach(item => {
            if (item.id === row.id) {
              this.$refs.multipleTable.toggleRowSelection(item, false)
            }
          })
          this.$nextTick(() => {
            this.selectedData.forEach((item, index) => {
              if (item.id === row.id) {
                this.selectedData.splice(index, 1)
              }
            })
          })
        }
      } else {
        this.selectedData.push(row)
        this.$nextTick(() => {
          this.selectedData.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        })
      }
    },
    deleteChose(index, row) {
      this.selectedData.splice(index, 1)
      this.$nextTick(() => {
        this.tableData.forEach(e => {
          if (e.id === row.id) {
            this.$refs.multipleTable.toggleRowSelection(e, false)
          }
        })
      })
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.selectedData.filter(item => row.id === item.id)
      return (filterArr.length > 0) ? 'selected-highlight' : ''
    }
  }
}
</script>

<style scoped lang="scss">

</style>
